package com.shenzhen.horselive.ui.activity;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Pair;
import android.view.View;

import com.flqy.baselibrary.utils.GlideHelper;
import com.flqy.baselibrary.utils.T;
import com.shenzhen.horselive.R;
import com.shenzhen.horselive.User;
import com.shenzhen.horselive.api.ApiFactory;
import com.shenzhen.horselive.api.response.MyInfoResponse;
import com.shenzhen.horselive.base.AppBarActivity;
import com.shenzhen.horselive.beans.CommResponseBean;
import com.shenzhen.horselive.beans.IsBindBean;
import com.shenzhen.horselive.common.SafeConsumer;
import com.shenzhen.horselive.common.utils.Permissions;
import com.shenzhen.horselive.databinding.ActivityUserInfoBinding;
import com.shenzhen.horselive.network.SchedulersCompat;
import com.shenzhen.horselive.presenter.LoadingViewObserver;
import com.shenzhen.horselive.ui.dialog.CommentDialog;
import com.shenzhen.horselive.utils.DialogManager;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;

import java.io.File;
import java.util.List;

import gun0912.tedbottompicker.PhotoPicker;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

public class UserInfoActivity extends AppBarActivity {

    private static final int REQUEST_CODE_CHOOSE =9001 ;
    ActivityUserInfoBinding  binding;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityUserInfoBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        setStyleDark();
        setTitle("个人信息");
        initViews();
        initData();
    }

    private void initData() {
        ApiFactory.getApiService().getUserInfo(User.get().getMyInfo().getToken())
        .compose(SchedulersCompat.applyIoSchedulers())
                .safeSubscribe(new LoadingViewObserver<IsBindBean>(this) {
                    @Override
                    protected void onNextInActive(IsBindBean bean) {
                        if (bean.isSuccess())
                        {
                            if (bean.getData()!=null)
                            {
                                User.get().storeMyInfo(bean.getData());
                                GlideHelper.loadAdvertImage(bean.getData().getHeadimgurl(),binding.imgUserHead);
//                                binding.tvName.setText(bean.getData().getNickname());
                                binding.etName.setText(bean.getData().getNickname());
                                if ("UNSET".equals(bean.getData().getPayPassword()))
                                {
                                    binding.tvSetPass.setText("未设置");
                                }
                                else
                                { binding.tvSetPass.setText("已设置");

                                }

                                if (bean.getData().getAliId()==null)
                                {
                                    binding.tvSetAli.setText("未设置");
                                }
                                else
                                { binding.tvSetAli.setText("已设置");

                                }

                                if (bean.getData().getCardNo()==null)
                                {
                                    binding.tvSetBank.setText("未设置");
                                }
                                else
                                {
                                    binding.tvSetBank.setText("已设置");
                                }


                            }
                        }
                    }
                });
    }

    String  path;
    CommentDialog  commentDialog;
    //初始化
    private void initViews() {
        //设置头像
      binding.imgUserHead.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View v) {

              Permissions.of(UserInfoActivity.this).request(getString(R.string.take_photo_get_sdcard_error),
                      Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE).subscribe(new SafeConsumer<Boolean>() {
                  @Override
                  public void accept(Boolean granted) {
                      if (granted) {
                          //权限申请成功

                          //权限申请成功
                          Matisse.from(UserInfoActivity.this)
                                  .choose(MimeType.ofImage())
                                  .countable(false)
                                  .maxSelectable(1)
                                  .showSingleMediaType(true)
//                                    .addFilter(new GifSizeFilter(320, 320, 5 * Filter.K * Filter.K))
//                                    .gridExpectedSize(getResources().getDimensionPixelSize(R.dimen.grid_expected_size))
//                                    .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
//                                    .thumbnailScale(0.85f)
                                  .imageEngine(new GlideEngine())
                                  .forResult(REQUEST_CODE_CHOOSE);


//                          new PhotoPicker.Builder(UserInfoActivity.this).setSelectMaxCount(1)
//                                  .setOnImageSelectedListener(new PhotoPicker.OnImageSelectedListener() {
//                                      @Override
//                                      public void onImageSelected(Pair<Uri, String> imagePath) {
//                                          path =  imagePath.second;
//                                          GlideHelper.loadImage(path,binding.imgUserHead);
//
//
//                                      }
//                                  }).create().show();
                      } else {
                          //权限申请失败
                          T.showShort("权限申请失败");
                      }
                  }
              });
          }
      });

      //设置支付密码
      binding.tvSetPass.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View v) {
              startActivityForResult(new Intent(getContext(),PassWordActivity.class),1000);
          }
      });

      //阿里账号
      binding.tvSetAli.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View v) {
              startActivityForResult(new Intent(getContext(),MyAliPayActivity.class),1000);
          }
      });

      //英航卡
        binding.tvSetBank.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (User.get().getMyInfo().getRealNameStatus()!=1)
                {
                    DialogManager.getInstance().showCommentDialog(getContext(), "你还未实名认证，是否去实名？"
                            , "", new CommentDialog.OnClickButton() {
                                @Override
                                public void confirm() {
                                    startActivityForResult(new Intent(getContext(),RealNameAuthActivity.class),1000);
                                }

                                @Override
                                public void cancel() {

                                }
                            }
                    );

                }
                else
                startActivityForResult(new Intent(getContext(),MyBankActivity.class),1000);
            }
        });

        binding.btGo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                submit();
            }
        });


    }

    private void submit() {
        String  nickname =  binding.etName.getText().toString();
        if (TextUtils.isEmpty(nickname)||nickname.length()>20)
        {
            return;
        }
        MultipartBody.Builder multipartBodyBuild = new MultipartBody.Builder()
                .addFormDataPart("nickname",nickname)
                .addFormDataPart("token", User.get().getMyInfo().getToken())
                .setType(MultipartBody.FORM);
       if (path!=null)
       {
           File  file =new File(path);
           RequestBody fileBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
           multipartBodyBuild.addFormDataPart("headimg", file.getName(), fileBody);
       }
       MultipartBody  multipartBody = multipartBodyBuild.build();
        ApiFactory.getApiService().saveHeadAndName(multipartBody)
                .compose(SchedulersCompat.applyIoSchedulers())
                .safeSubscribe(new LoadingViewObserver<CommResponseBean>(this) {
                    @Override
                    protected void onNextInActive(CommResponseBean commResponseBean) {
                        if (commResponseBean.isSuccess())
                        {
                            showToast("保存成功");
                            setResult(1001);
                            finish();
                        }
                        else
                        {
                            showToast(commResponseBean.getErrMessage());
                        }
                    }
                });

    }


    List<String>  mSelected;
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==1000&&resultCode==1001)
        {
            //更新数据
           initData();
        }
        if (requestCode == REQUEST_CODE_CHOOSE && resultCode == RESULT_OK) {
//            mSelected = Matisse.obtainResult(data);
            mSelected =   Matisse.obtainPathResult(data);
            if (mSelected!=null&&mSelected.size()>0)
            {
                path =  mSelected.get(0);
               GlideHelper.loadImage(path,binding.imgUserHead);
//
            }
        }
    }
}